<template>
  <div class="pie-gadget-css" style="width:100%;height:100%" :id="id">
    <Portal to="right-disable"
            style="width:100%;height:100%"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  class="aui-card--fill"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  style="width:100%;height:100%; border:0">

        <el-card shadow="never"
                 v-loading="loading"
                 style="width:100%;height:100%; border:0"
                 class="aui-card--fill">
          <div style="width:100%;height:100%;">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName && widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <div>
                <MoreMenu
                  ref="moreMenu"
                  :slicer='slicer'
                  :fitToHeight='fitToHeight'
                  :gadgetId='id'
                  :gadgetType='gadgetInfo.com'
                  @updateQuery="query"
                  :widgetName="widgetName"
                  :businessType="gadgetInfo.businessType"
                  :id="gadgetInfo.id"
                  @showQueryModel="showQueryModel"
                  @fullScreen="fullScreen" 
                />
              </div>
            </div>
            <div class="control-section control-section2">
              <div class="content-wrapper content-card"
                   style="width:100%;height:100%;">
<!--                <div id="york" v-else style="width:100%;height:100%;"></div>-->
                <div v-if="isHasData"
                     style="width:100%;height:100%;">
                     <div class="echarts-title" style="height:30px;line-height: 30px;font-size:16px;font-weight:700;text-align:center">{{gadgetSetting.title}}</div>
                     <div :id="selfGadgetUuid" style="width:100%;height:calc(100% - 30px);"></div>
                </div>
                <div v-else
                    class="gadget-no-newdata">
                    <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"  :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
                </div>
              </div>
            </div>

          </div>
        </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>

    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           :slicer='slicer' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
    <div style="position:absolute;left:9999px;">
      <component v-for="(item, index) in formatComponentList"
                 :key="index"
                 :is="item"
                 :ref="item"
                 gadgetType='notgridgadget' />
    </div>
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import {defaultGadgetSettingList} from '@/utils/data-json'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import {getUUID} from '@/utils'
import * as Echarts from 'echarts'

export default ({
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: { Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model') },
  data: function () {
    return {
      selfGadgetUuid: getUUID(),
      repeatNumber: 0,
      chartDom: null,
      currentTime: null,
      queryData: [],
      queryFields: [],
      theme: 'Material',
      dataSource: [],
      gadgetSetting: null,
      loading: false,
      chartWidth: '600px',
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'sunburstgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'sunburstgadget' }).gadgetSetting
        }
      },
      queryId: '',
      queryDrillthrough: {},
      widgetName: '',
      linkedDatasetList: []
    }
  },
  created () {
    // this.gadgetHeight = (this.gadgetInfo.h * 20) - 45
    // this.query()
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
  },
  methods: {
    formatDataToEchart (data) {
      const X = this.gadgetSetting.dimension
      const Y = this.gadgetSetting.measure
      let formatData = []
      data.filter(v => v[X] !== null || v[Y] !== null).forEach(item => {
        const obj = {
          name:item[X],
          value:item[Y]
        }
        const Index = formatData.findIndex((v) => {
          return v.name === obj.name
        })
        if(Index < 0){
          formatData.push(obj)
        }else{
          formatData[Index].value += parseFloat(obj.value)
        }

        
      })
      let result = (this.gadgetSetting.resultData && this.gadgetSetting.resultData.length > 0 ? this.gadgetSetting.resultData : formatData)
      return {
        formatData:result,
        // title: this.gadgetSetting.title,
        dimension: this.gadgetSetting.dimension,
        measure: this.gadgetSetting.measure,
        radius: this.gadgetSetting.radius,
        sort: this.gadgetSetting.sort,
        showLabel: this.gadgetSetting.showLabel,
        align: this.gadgetSetting.align,
        minAngle:this.gadgetSetting.minAngle
      }
    },
    labelFormat (params) {
      const treePathInfo = params.treePathInfo
      const fatherValue = treePathInfo[0].value
      const Token = {
        CurrentDimensionName: params.name === null ? 'null' : params.name,
        ParentDimensionMeasureValue: treePathInfo.length - 2 > 0 ? treePathInfo[treePathInfo.length - 2].value : '',
        MeasurePercentage: (params.value / fatherValue * 100).toFixed(2) + '%',
        CurrentDimensionMeasureValue: params.value
      }
      let html = this.gadgetSetting.quillContent.replace('<span class="ql-cursor">﻿</span>', '').replace(/<p>/g, '').split('</p>').filter(item => item)
      if (treePathInfo.length === 1) {
        return []
      }
      return html.map(item => {
        const regex = /\{(.*?)\}/g;
        const token = item.match(regex)
        token?.map(items => {
          const key = items.substring(1, items.length - 1)
          item = item.replace(items, `${Token[key]}`)
        })
        item = item.replace(/<br>/g, '\n')
        item = item.replace(/<em>/g, '{em|')
        item = item.replace(/<\/em>/g, '}')
        item = item.replace(/<strong>/g, '{strong|')
        item = item.replace(/<\/strong>/g, '}')
        return item
      })
    },
    updateChart (originData) {
      this.chartDom = document.getElementById(`${this.selfGadgetUuid}`)
      if (!this.chartDom) {
        setTimeout(() => {
          this.repeatNumber++
          this.updateChart(originData)
        }, 1000)
      } else if (!Array.isArray(originData) || (Array.isArray(originData) && originData.length === 0)) {
        Echarts.init(this.chartDom).dispose()
      } else {
        const echartsData = this.formatDataToEchart(originData)
        let myChart = Echarts.init(this.chartDom, this.globalTheme)
        const option = {
          // title: {
          //   text: this.gadgetSetting.title || '',
          //   left: 'center'
          // },
          series: [
            {
              type: 'sunburst',
              data: echartsData.formatData,
              radius:[0,this.gadgetSetting.radius + '%'],
              sort:this.gadgetSetting.sort,
              label: {
                align:this.gadgetSetting.align,
                minAngle:this.gadgetSetting.minAngle,
                show: echartsData.showLabel,
                formatter:(params) => {
                  return this.labelFormat(params).join('\n')
                },
                rich: {
                  strong: {
                    fontWeight: 'bold'
                  },
                  em: {
                    fontStyle: 'italic'
                  }
                }
              },
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        this.isTotal(option)
        option && myChart.setOption(option)
        // myChart.on('click', params => {
        //   this.setDrillThroughInfo(params, this.queryModelDefaultSetting.dataInfo.gadgetType, originData)
        // })
        this.$erd.listenTo(this.chartDom, element => {
          this.$nextTick(() => {
            this.resized()
          })
        })
      }
    },
    isTotal (option) {
      let yGrandTotal = 0
      if (this.gadgetSetting.isTotal) {
        option.yAxis.data.push('Grand Total')
        let dataX = this._.cloneDeep(option.series[0].data)

        for (let i = 0; i < option.xAxis.data.length; i++) {
          const a = option.series[0].data.filter(num => num[0] === i)
          let b = a.reduce((pre, curr) => {
            pre += curr[2]
            return pre
          }, 0)
          yGrandTotal += b
          option.series[0].data.push([i, option.yAxis.data.length - 1, b])
        }

        option.xAxis.data.push('Grand Total')

        for (let i = 0; i < option.yAxis.data.length - 1; i++) {
          const a = dataX.filter(num => num[1] === i)
          let b = a.reduce((pre, curr) => {
            pre += curr[2]
            return pre
          }, 0)
          option.series[0].data.push([option.xAxis.data.length - 1, i, b])
        }
        option.series[0].data.push([option.xAxis.data.length - 1, option.yAxis.data.length - 1, yGrandTotal])
      }
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      setTimeout(() => {
        let myChart = Echarts.init(this.chartDom, this.globalTheme)
        myChart.resize()
      }, 0)
      // this.gadgetHeight = (newH * 20) - 45
      // this.gadgetWidth = newWPx
      // this.chartWidth = (newWPx - 10) + 'px'
      // this.$nextTick(() => {
      //   if (this.chartDom) {
      //     let myChart = Echarts.init(this.chartDom)
      //     myChart.resize({
      //       width: this.gadgetWidth * 0.94,
      //       height: this.gadgetHeight - 30 * 2 - 34
      //     })
      //   }
      // })
    },
    containerResizedEvent (i, newH, newW, newHPx, newWPx) {
      this.chartWidth = (newWPx - 10) + 'px'
    },
    query (e) {
      this.gadgetSetting = this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      if (e !== 'auto') {
        this.loading = true
      }
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        try {
          _self.$parent.$parent.$parent.$parent.$parent.$parent.selectFields = res.selectFields
        } catch (error) {

        }
        this.currentTime = new Date()
        _self.verifyHasData(res)
        if (res.config) {
          _self._.merge(_self.gadgetSetting, res.config)
        }
        if (!_self.gadgetSetting.headerDescription || _self.gadgetSetting.headerDescription === null) {
          _self.gadgetSetting.headerDescription = ''
        }
        if (res.name) {
          _self.widgetName = res.name
        } else if (this.wName) {
          _self.widgetName = this.wName
        } else {
          _self.widgetName = _self.gadgetSetting.headerTitle
        }
        this.fxFields = res.fxFields || []
        if (res.data) {
          _self.currentTime = new Date()
          _self.updateChart(res.data)
          _self.queryData = res.data
          _self.queryFields = res.selectFields
          _self.linkedDatasetList = res.datasetSync
          this.$root.eventBus.$emit('sunburst-data',res.data)
        }
      }).catch((error) => {
          if (this.wName) {
          this.widgetName = this.wName
        }
        this.loading = false
        if (error.response && error.response.status === 504) {
          this.errorStatus = '504'
          this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
        }
      }).finally(() => {
        this.autoRefreshQuery(e)
        this.updateGadgetLoadingStatus(!this.loading)
      })
    }
  }
})
</script>
<style lang="scss" scoped>
.content-card {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 40%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}
</style>
<style lang="scss">
.pie-gadget-css {
  .el-card__body {
    width: 100%;
    height: 100%;
  }
  .control-section2 {
    width: 100%;
    height: calc(100% - 34px);
  }
}
</style>
